package Servlets.yz;

import Bean.Admin;
import Bean.User;
import Util.GokJDBCUtil2;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

@WebServlet(name="UserLoginServlet",urlPatterns = "/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sqlUser = "select * from user where username=? and userpassword=?";
        String sqlAdmin = "select * from admin where adminaccount=? and adminpassword=?";
        User user = GokJDBCUtil2.queryForObject(sqlUser, User.class, username, password);
        Admin admin = GokJDBCUtil2.queryForObject(sqlAdmin, Admin.class, username, password);

        if(admin != null ){
            HttpSession adminSession = req.getSession();
            adminSession.setAttribute("admin",admin.getAdminstatus());
            LocalDateTime updateTime = LocalDateTime.now();//获取现在的时间
            String sql = "update admin set updatetime=? where adminaccount=?";
            GokJDBCUtil2.update(sql,updateTime,username);
            /*指向管理员的页面*/
            req.getRequestDispatcher("pages/adminIndex.jsp").forward(req,resp);
        }
        else if(user !=null){
            HttpSession userSession = req.getSession();
            userSession.setAttribute("admin",0);
            userSession.setAttribute("user",user);
            LocalDateTime updateTime = LocalDateTime.now();//获取现在的时间
            String sql = "update user set updatetime=? where username=?";
            GokJDBCUtil2.update(sql,updateTime,username);
            /*指向用户页面--跳转页面待修改*/
            req.getRequestDispatcher("pages/test.jsp").forward(req,resp);
        }
        else{
            resp.sendRedirect(req.getContextPath()+"/pages/userLogin.jsp");
        }
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
